// 封装axios
import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router";
import { getToken } from "./token/index.js";

const request = axios.create({
    baseURL: 'http://localhost:8081',
    withCredentials: false, // 配置跨域是否需要凭证
    timeout: 30000,

})
// 设置请求头编码格式
request.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 配置请求拦截器
request.interceptors.request.use((config) => {
        // console.log("token", getToken('token'));
        // 在sessionStorage中查找token，如果有在请求头添加token
        if(getToken('token')) {
            config.headers['Authorization'] = getToken('token');
            // console.log('request interceptors token = ', getToken('token'))
        }
        return config;
    },
    (error) => {
        console.error(error);
        return Promise.reject(error);
    }
)

// 配置响应拦截器
request.interceptors.response.use((response) => {
    let {code, msg} = response.data;    
    if (code == 200 || code == null) {
        console.log('response data', response.data);
        return response;
    }else if (code == 500) {
        ElMessage.error('服务器出现异常')
    }else if (code == 100) {
        ElMessage.warning('请稍后重试')
    }else if (code == 101) {
        ElMessage.error('登陆已过期，请重新登陆')
        window.sessionStorage.clear()
        router.push('/login')
    }
    return Promise.reject(msg)
}, (error) => {
    ElMessage.error(error)
    window.sessionStorage.clear()
    router.push('/login')
    return Promise.reject(error)
}
)

export default request;